import { Module } from "vuex";
import { login, logout, getUserInfo, refreshToken } from "@/api/auth";
import {
  setToken,
  setRefreshToken,
  setUserInfo,
  getToken,
  getRefreshToken,
  clearAuth,
} from "@/utils/auth";
import type { User, LoginRequest, AuthResponse } from "@/types";

interface AuthState {
  user: User | null;
  token: string | null;
  refreshToken: string | null;
  isAuthenticated: boolean;
  loading: boolean;
}

const authModule: Module<AuthState, Record<string, unknown>> = {
  namespaced: true,

  state: {
    user: null,
    token: getToken() || null,
    refreshToken: getRefreshToken() || null,
    isAuthenticated: !!getToken(),
    loading: false,
  },

  getters: {
    user: state => state.user,
    token: state => state.token,
    isAuthenticated: state => state.isAuthenticated,
    loading: state => state.loading,
    userRoles: state => state.user?.roles || [],
    userPermissions: state => {
      // 由于roles现在是string[]，暂时返回基本权限
      if (!state.user?.roles) return [];
      const permissions: string[] = [];
      if (state.user.roles.includes("SYSTEM_ADMIN")) {
        permissions.push(
          "admin:read",
          "admin:write",
          "admin:delete",
          "system:manage",
          "users:manage"
        );
      } else if (state.user.roles.includes("ADMIN")) {
        permissions.push("admin:read", "admin:write", "admin:delete");
      }
      if (state.user.roles.includes("USER")) {
        permissions.push("user:read", "user:write");
      }
      return permissions;
    },
  },

  mutations: {
    SET_LOADING(state, loading: boolean) {
      state.loading = loading;
    },

    SET_USER(state, user: User) {
      state.user = user;
      state.isAuthenticated = true;
      setUserInfo(user);
    },

    SET_TOKEN(state, tokenData: { token: string; refreshToken: string }) {
      state.token = tokenData.token;
      state.refreshToken = tokenData.refreshToken;
      state.isAuthenticated = true;
      setToken(tokenData.token);
      setRefreshToken(tokenData.refreshToken);
    },

    CLEAR_AUTH(state) {
      state.user = null;
      state.token = null;
      state.refreshToken = null;
      state.isAuthenticated = false;
      clearAuth();
    },

    UPDATE_USER(state, userData: Partial<User>) {
      if (state.user) {
        state.user = { ...state.user, ...userData };
        setUserInfo(state.user);
      }
    },
  },

  actions: {
    // 用户登录
    async login({ commit }, loginData: LoginRequest) {
      commit("SET_LOADING", true);
      try {
        const response: AuthResponse = await login(loginData);

        // 设置token
        commit("SET_TOKEN", {
          token: response.accessToken,
          refreshToken: response.refreshToken,
        });

        // 转换用户信息格式
        console.log("登录响应中的用户角色数据:", response.userInfo.roles);
        console.log("登录响应完整数据:", response.userInfo);

        // 确保角色数据存在且为数组，直接提取角色名称
        const rolesData = response.userInfo.roles || [];
        console.log("处理前的角色数据:", rolesData);

        const processedRoles = rolesData.map((role: any) => {
          console.log("处理单个角色:", role);
          // 兼容不同的角色数据格式，只返回角色名称
          if (typeof role === "string") {
            return role;
          } else if (role && typeof role === "object") {
            return role.name || role.roleName || "USER";
          }
          return "USER";
        });

        console.log("处理后的角色数据:", processedRoles);

        const user: User = {
          id: response.userInfo.id,
          username: response.userInfo.username,
          email: response.userInfo.email,
          nickname: response.userInfo.nickname,
          avatar: response.userInfo.avatar,
          roles: processedRoles,
          createTime: response.userInfo.lastLoginTime || "",
          updateTime: response.userInfo.lastLoginTime || "",
          isActive: true,
        };

        console.log("最终用户对象:", user);

        // 设置用户信息
        commit("SET_USER", user);

        return response;
      } catch (error) {
        commit("CLEAR_AUTH");
        throw error;
      } finally {
        commit("SET_LOADING", false);
      }
    },

    // 用户登出
    async logout({ commit }) {
      commit("SET_LOADING", true);
      try {
        await logout();
      } catch (error) {
        console.error("Logout error:", error);
      } finally {
        commit("CLEAR_AUTH");
        commit("SET_LOADING", false);
      }
    },

    // 获取用户信息
    async fetchUserInfo({ commit }) {
      try {
        const userInfo = await getUserInfo();

        // 转换为完整的User对象
        console.log("获取用户信息中的角色数据:", userInfo.roles);
        console.log("获取用户信息完整数据:", userInfo);

        // 确保角色数据存在且为数组，直接提取角色名称
        const rolesData = userInfo.roles || [];
        console.log("fetchUserInfo处理前的角色数据:", rolesData);

        const processedRoles = rolesData.map((role: any) => {
          console.log("fetchUserInfo处理单个角色:", role);
          // 兼容不同的角色数据格式，只返回角色名称
          if (typeof role === "string") {
            return role;
          } else if (role && typeof role === "object") {
            return role.name || role.roleName || "USER";
          }
          return "USER";
        });

        console.log("fetchUserInfo处理后的角色数据:", processedRoles);

        const user: User = {
          id: userInfo.id,
          username: userInfo.username,
          email: userInfo.email,
          nickname: userInfo.nickname,
          avatar: userInfo.avatar,
          roles: processedRoles,
          createTime: userInfo.lastLoginTime || "",
          updateTime: userInfo.lastLoginTime || "",
          isActive: true,
        };

        console.log("fetchUserInfo最终用户对象:", user);

        commit("SET_USER", user);
        return user;
      } catch (error) {
        commit("CLEAR_AUTH");
        throw error;
      }
    },

    // 刷新token
    async refreshToken({ commit, state }) {
      if (!state.refreshToken) {
        throw new Error("No refresh token available");
      }

      try {
        const response: AuthResponse = await refreshToken(state.refreshToken);
        commit("SET_TOKEN", {
          token: response.accessToken,
          refreshToken: response.refreshToken,
        });
        return response;
      } catch (error) {
        commit("CLEAR_AUTH");
        throw error;
      }
    },

    // 更新用户信息
    updateUser({ commit }, userData: Partial<User>) {
      commit("UPDATE_USER", userData);
    },

    // 初始化认证状态
    initAuth({ commit, dispatch }) {
      const token = getToken();
      if (token) {
        commit("SET_TOKEN", { token, refreshToken: getRefreshToken() || "" });
        // 获取用户信息
        dispatch("fetchUserInfo").catch(() => {
          commit("CLEAR_AUTH");
        });
      }
    },
  },
};

export default authModule;
